package com.eastchina.fids2focs.common.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.eastchina.fids2focs.common.GlobalConstants;

public class ResourceManager {

	/**
	 * system properties files
	 */
	protected static final String PROPFILE_SYS = "system-properties.properties";
	/**
	 * messages properties files
	 */
	protected static final String PROPFILE_MSG = "system-messages.properties";
	
    /**
     * The set of previously created MessageFormat objects
     */
    protected Map<String, MessageFormat> formats = new HashMap<String, MessageFormat>();

    /**
     * ResourceManager instance
     */
    private static ResourceManager instance = new ResourceManager();
    
    /**
     * Commons Logging instance.
     */
	private static final Log log = LogFactory.getLog(ResourceManager.class);
	
	/**
	 * Construct a new ResourceManager
	 */
    public ResourceManager() {
    	load(PROPFILE_SYS);
    	
    	String international = get("lang.international");
    	if (international != null && "true".equals(international.toLowerCase())) {
    		Locale defaultLocale = Locale.getDefault(); 
    		if (defaultLocale != null) {
        		int index = PROPFILE_MSG.lastIndexOf(".");
        		String conf = PROPFILE_MSG.substring(0, index)
        			+ "_" + defaultLocale.getLanguage() 
        			+ "_" + defaultLocale.getCountry()
        			+ PROPFILE_MSG.substring(index);
        		load(conf);    			
    		} else {
    			load(PROPFILE_MSG);
    		}
    	} else {
        	load(PROPFILE_MSG);    		
    	}
    }
    
    /**
     * Returns the ResourceManager instance
     */
    public static ResourceManager getInstance() {
    	return instance;
    }

    /**
     * Returns a text message for the specified key
     * @param key The message key to look up
     * @param args An array of replacement parameters for placeholders
     */
	public static String getMessage(String key, Object... args) {
		return ResourceManager.getInstance().get(key, args);
	}
	
    /**
     * Returns a text message after parametric replacement of the specified
     * parameter.
     *
     * @param key  The message key to look up
     * @param args An array of replacement parameters for placeholders
     */
	public final String get(String key, Object... args) {
		MessageFormat format = formats.get(key);
		if (format == null) {
			return null;
		}
		
		return format.format(args);
	}
	
    /**
     * Load the properties
     * @param config a fully qualified package and resource name
     */
    private void load(String config) {
    	Properties p = new Properties();

    	ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    	if (classLoader == null) {
    		classLoader = ResourceManager.class.getClassLoader();
    	}
    	InputStream is = classLoader.getResourceAsStream(config);

    	if (is != null) {
    		try {
				p.load(is);
			} catch (IOException ioe) {
				log.error("load()", ioe);
			} finally {
				try {
					is.close();
				} catch (IOException ioe) {
					log.error("load()", ioe);
				}
			}
    	}
    	
    	if (p.size() < 1) {
    		return;
    	}
    	
    	synchronized (formats) {
            Iterator<Object> names = p.keySet().iterator();
            while (names.hasNext()) {
                String key = (String) names.next();
                String value = p.getProperty(key);
                try {
					value = new String(value.getBytes("ISO8859-1"), GlobalConstants.DEFAULT_ENCODING);
				} catch (UnsupportedEncodingException e) {
				}
                
                formats.put(key, new MessageFormat(value));
            }
		}
    }	
}
